package cn.tedu.egarticle.controller;

import cn.tedu.egarticle.base.response.JsonResult;
import cn.tedu.egarticle.base.response.StatusCode;
import cn.tedu.egarticle.mapper.UserMapper;
import cn.tedu.egarticle.pojo.dto.UserArticleParam;
import cn.tedu.egarticle.pojo.dto.UserLoginParam;
import cn.tedu.egarticle.pojo.entity.Article;
import cn.tedu.egarticle.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/v1/user/")
@Api(tags = "01.用户管理模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("login")
    @ApiOperation("登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("UserLoginParam = "+ userLoginParam);
        //先判断用户名和密码是否错误
        UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
        if(userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }else {
            session.setAttribute("user777888XXX",userVO);
            return JsonResult.ok(userVO);
        }
    }

    @PostMapping("article")
    @ApiOperation("发表文章功能")
    @ApiOperationSupport(order = 20)
    public JsonResult article(@Validated @RequestBody UserArticleParam userArticleParam, @ApiIgnore HttpSession session){
        log.debug("UserArticleParam = "+ userArticleParam);
        UserVO userVO = (UserVO) session.getAttribute("user777888XXX");
        //复制数据
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam,article);
        article.setUserId(userVO.getId());
        int rows = userMapper.insertArticle(article);
        if(rows == 0){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }else {
            return JsonResult.ok();
        }
    }
}
